package com.smartsofa.main;

import java.io.File;
import java.net.URI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.smartsofa.R;
import com.smartsofa.util.MyUtils;
import com.smartsofa.util.Tools;

public class AddFamilyGroup extends Activity{
	/* 请求码 */
	private static final int IMAGE_REQUEST_CODE = 0;
	private static final int CAMERA_REQUEST_CODE = 1;
	/* 头像名称 */
	private static final String IMAGE_FILE_NAME = "family_img.jpg";
	//图片转化为字符串
	private String photostr;
	private Bitmap photo;
	String baseDir;
	
	private String[] items = new String[] { "选择本地图片", "拍照" };
	
	private Button bt_back;
	private ImageView family_img;
	private EditText et_family_name;
	private EditText et_family_sign;
	private Button bt_submit;
	
	private String family_name;
	private String family_sign;
	private Boolean flag=false;
	private String reg_msg;
	//定义网络连接超时判定变量
	private boolean network_timeout=false;
	private ProgressDialog mDialog;	
	private Intent intent;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_family);
		initView();
	}
	
	private void initView(){
		bt_back=(Button) findViewById(R.id.back);
		family_img=(ImageView) findViewById(R.id.add_family_img);
		et_family_name=(EditText) findViewById(R.id.et_family_name);
		et_family_sign=(EditText) findViewById(R.id.et_family_sign);
		bt_submit=(Button) findViewById(R.id.bt_submit);
		
		bt_back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				AddFamilyGroup.this.finish();
			}
		});
		family_img.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				showDialog(); 
			}
		});
		bt_submit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				family_name=et_family_name.getText().toString().trim();
				family_sign=et_family_sign.getText().toString().trim();
				boolean netstate=MyUtils.isNetworkConnected(getApplicationContext());
				if(!netstate){
					Toast.makeText(getApplicationContext(),"网络无法连接，请检查您的网络！",Toast.LENGTH_SHORT).show();
				}else if(family_name.equals("")){
					Toast.makeText(getApplicationContext(), "家庭租的名称不能为空！", Toast.LENGTH_SHORT).show();
				}else if(family_sign.equals("")){
					Toast.makeText(getApplicationContext(), "个性签名可以使得家庭组更具有吸引力哦！", Toast.LENGTH_SHORT).show();
				}
				else{
					mDialog = new ProgressDialog(AddFamilyGroup.this);
					mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
					mDialog.setMessage("正在处理，请稍候...");
					mDialog.show();
					Thread thread=new Thread(new addFamily_thread());
					thread.start();
				}
			}
		});
	}
	
	/**
	 * 显示选择对话框
	 */
	private void showDialog() {

		new AlertDialog.Builder(this)
				.setTitle("设置头像")
				.setItems(items, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0://选择本地图片
							Intent intentFromGallery = new Intent();
							intentFromGallery.setType("image/*"); // 设置文件类型
							intentFromGallery
									.setAction(Intent.ACTION_GET_CONTENT);
							startActivityForResult(intentFromGallery,
									IMAGE_REQUEST_CODE);
							break;
						case 1://拍照
							destoryBimap();
							Intent intentFromCapture = new Intent(
									MediaStore.ACTION_IMAGE_CAPTURE);
							// 判断存储卡是否可以用，可用进行存储
							if (Tools.hasSdcard()) {

								intentFromCapture.putExtra(
										MediaStore.EXTRA_OUTPUT,
										Uri.fromFile(new File(Environment
												.getExternalStorageDirectory(),
												IMAGE_FILE_NAME)));
							}

							startActivityForResult(intentFromCapture,
									CAMERA_REQUEST_CODE);
							break;
						}
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).show();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		 super.onActivityResult(requestCode, resultCode, data); 
		//结果码不等于取消时候
		if (resultCode != RESULT_CANCELED) {
			switch(requestCode){
			case IMAGE_REQUEST_CODE:
				startPhotoZoom(data.getData());
				break;
			case CAMERA_REQUEST_CODE:
				if (Tools.hasSdcard()) {
					File tempFile = new File(
							Environment.getExternalStorageDirectory()
									,IMAGE_FILE_NAME);
					startPhotoZoom(Uri.fromFile(tempFile));
				} else {
					Toast.makeText(getApplicationContext(), "未找到存储卡，无法存储照片！",
							Toast.LENGTH_LONG).show();
				}
				break;
			case 2:
				if (data != null) {
					getImageToView(data);
				}
				break;
			}

            super.onActivityResult(requestCode, resultCode, data);
		}
	}
	
	private void destoryBimap() { 
        if (photo != null && !photo.isRecycled()) { 
            photo.recycle(); 
            photo = null; 
        } 
}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 设置裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 640);
		intent.putExtra("outputY", 640);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 2);
	}
	
	/**
	 * 保存裁剪之后的图片数据
	 * 
	 * @param picdata
	 */
	private void getImageToView(Intent data) {
		Bundle extras = data.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
			BitmapDrawable drawable = new BitmapDrawable(photo);		
			family_img.setImageDrawable(drawable);
			photostr=MyUtils.convertIconToString(photo);
			//MyUtils.setPicToStore(MyUtils.getUSERID(),photo);
		    Thread thread = new Thread(new addFamily_thread());
		    thread.start();
		}
	}

	
	class addFamily_thread implements Runnable{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {			
				String url=MyUtils.getUrl()+"family_createFamily";
				HttpPost post = new HttpPost(new URI(url));	            
	            JSONObject json = new JSONObject();
	            json.put("fileData", photostr);
	            json.put("userId", MyUtils.getUSERID());
	            json.put("familyName", family_name);
	            json.put("signature", family_sign);
				post.setEntity(new StringEntity(json.toString(),"utf-8"));
				BasicHttpParams httpParams = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParams,MyUtils.REQUEST_TIMEOUT);
			    HttpClient httpClient = new DefaultHttpClient(httpParams);
	            HttpResponse httpResponse = httpClient.execute(post);
		       	
		      if (httpResponse.getStatusLine().getStatusCode() == 200) {
		    	  network_timeout=true;
		    	  HttpEntity entity = httpResponse.getEntity();
		    	  if(entity!=null){
		    		  // 获取服务器响应的json字符串
		    		  String jsonString = EntityUtils.toString(httpResponse.getEntity());
		    		  Log.i("jsonString:", jsonString);
			          JSONObject return_json = new JSONObject(jsonString);
			          flag=return_json.getBoolean("success");
			          reg_msg=return_json.getString("msg");
			          Message msg = content_handler.obtainMessage();
						if(network_timeout){
							if (flag) {				
								msg.what = 1;									
							}else{
								msg.what = 2;			
							}
						}			
						else{
							msg.what = 3;						
						}
						content_handler.sendMessage(msg);
		    	  }         
		      }
		      }catch (Exception e) {
		        	 e.printStackTrace();
		    }
		}		
	}
	Handler content_handler = new Handler() {
		public void handleMessage(Message msg) {
			mDialog.dismiss();
			switch (msg.what) {		
			case 1:	
			   	Toast.makeText(AddFamilyGroup.this,"建立家庭组成功！",Toast.LENGTH_SHORT).show();
			   	Intent intent=new Intent();
				Bundle bundle=new Bundle();
				bundle.putInt("selectionState", 3);
				intent.putExtra("attachment",bundle);
		     	intent.setClass(AddFamilyGroup.this, MainActivity.class);		     	
		     	startActivity(intent);
		     	AddFamilyGroup.this.finish();
		     	break;
			case 2:
				Toast.makeText(AddFamilyGroup.this,reg_msg.toString(),Toast.LENGTH_SHORT).show();
				break;
			case 3:
				Toast.makeText(AddFamilyGroup.this,"网络连接超时!",Toast.LENGTH_SHORT).show();
				break;
		     }
		}
	};
}
